package com.madzone.gae.filem;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

import javax.jdo.PersistenceManager;

import com.madzone.wiki.gae.ds.model.PMF;

public class FileOutputStream extends OutputStream {

	private String absolutePath;
	
	private ByteArrayOutputStream baos;
	public FileOutputStream(File file) {
		absolutePath = file.getAbsolutePath();
		baos = new ByteArrayOutputStream();
	}
	
	public FileOutputStream(String absolutePath) {
		this.absolutePath = absolutePath;
		baos = new ByteArrayOutputStream();
	}
	
	@Override
	public void write(int arg0) throws IOException {
		baos.write(arg0);
	}
	
	public void close() {
		PersistenceManager pm = PMF.getPM();
		byte[] content = baos.toByteArray();
		com.madzone.gae.filem.model.File gaeFile = null;
		gaeFile = com.madzone.gae.filem.model.BinaryFile.getByName(absolutePath);
		if (gaeFile != null) {
			gaeFile.setContentBytes(content);
		} else {
			gaeFile = new com.madzone.gae.filem.model.BinaryFile(absolutePath, content);
		}
		try {
			pm.makePersistent(gaeFile);
		} finally {
			//pm.close();
		}
	}

}
